package com.hello;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

public class Consumer {
    private final static String QUEUE_NAME = "test_queue";

    /**
     * basicPublish与basicConsume这些方法都是同步方法
     *
     * @param argv
     * @throws Exception
     */
    public static void main(String[] argv) throws Exception {
        System.out.println("threadName: " + Thread.currentThread().getName() + " thread count:" + Thread.activeCount());
        ConnectionFactory connectionFactory = new ConnectionFactory();
        // connectionFactory.setHost("localhost");
        //没有把connection与Channel放在try with resource代码块里，
        // 这样他们就不会自动调用close，就可以让程序不退出,以便其可以不断地接收信息

        System.out.println("before newConnection threadName: " + Thread.currentThread().getName() + " thread count:" + Thread.activeCount());
        //连接建立之后，会额外创建新的线程
        Connection connection = connectionFactory.newConnection();

        System.out.println("after new Connection before createChannel threadName: " + Thread.currentThread().getName() + " thread count:" + Thread.activeCount());
        // 创建信道一般不会额外创建线程
        Channel channel = connection.createChannel();
        //生产端已经声明了队列，不需要重复声明
        // channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        DeliverCallback callback = (consumerTag, delivery) -> {
            System.out.println(" 消费回调：threadName: " + Thread.currentThread().getName());
            String message = new String(delivery.getBody(), "UTF-8");
            //System.out.println("ConsumerTag： " + consumerTag);
            System.out.println(message);
        };
        System.out.println("after createChannel threadName: " + Thread.currentThread().getName() + " thread count:" + Thread.activeCount());
        //不会阻塞，不会因为没有消息就阻塞在这里
        // 调用basicConsume方法之后会额外创建线程以用来进行消息的接收处理
        channel.basicConsume(QUEUE_NAME, true, callback, consumerTag -> {
        });

        System.out.println("basic consume之后---线程：" + Thread.currentThread().getName() + " thread count:" + Thread.activeCount());
    }

}
